package com.cgc.dao.impl;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import org.springframework.transaction.annotation.Transactional;

import com.cgc.dao.IBaseDao;
import com.cgc.entity.Dept;

@Transactional
public class BaseDaoImpl<T> extends HibernateDaoSupport implements IBaseDao<T> {

	private Class<T> entityClas;

	private SessionFactory sessionFactory;

	public BaseDaoImpl() {
		Type baseDaoClass = this.getClass().getGenericSuperclass();
		// 转成带参数，即泛型的类的类型
		ParameterizedType pType = (ParameterizedType) baseDaoClass;
		// 获取参数泛型类型数组
		Type[] types = pType.getActualTypeArguments();
		entityClas = (Class<T>) types[0];
	}

	@Override
	public void add(T t) {
		this.getHibernateTemplate().save(t);
	}

	@Resource
	public void setSessionFacotry(SessionFactory sessionFacotry) {
		super.setSessionFactory(sessionFacotry);
	}

	@Override
	public List<T> getListByPage(T t1,int firstResult, int maxResult) {
		DetachedCriteria dc = getDetachedCriteria(t1);
		List<T> list = (List<T>) this.getHibernateTemplate().findByCriteria(dc, firstResult, maxResult);
		return list;
	}

	/**
	 * 由子类实现
	 * 
	 * @return
	 */
	public DetachedCriteria getDetachedCriteria(T t1) {
		return null;
	}

	@Override
	public long getCount(T t1) {
		DetachedCriteria dc = getDetachedCriteria(t1);
		dc.setProjection(Projections.rowCount());
		List<Long> list = (List<Long>) this.getHibernateTemplate().findByCriteria(dc);
		return list.get(0);
	}

	@Override
	public void delete(Integer id) {
		 T t = this.get(id);
		 this.getHibernateTemplate().delete(t);
	}

	@Override
	public T get(Integer id) {
		return this.getHibernateTemplate().get(entityClas, id);
	}

	@Override
	public void update(T t) {
		this.getHibernateTemplate().update(t);
	}

	@Override
	public List<T> getList(T t1) {
		DetachedCriteria dc = getDetachedCriteria(t1);
		List<T> list = (List<T>) this.getHibernateTemplate().findByCriteria(dc);
		return list;
	}

}
